package com.itfreer.gis.data.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.springframework.stereotype.Component;

@Component
public class GpsFileDataEditServerImp implements GpsFileDataEditServer {

	@Override
	public List<SimpleFeature> queryFeature(String source, String where) throws NoSuchAuthorityCodeException, FactoryException {
		File file = new File(source);
		String str = txt2String(file);
		String[] strPonts = str.split("\n");
		if (strPonts == null || strPonts.length <= 0) {
			return null;
		}

		List<Coordinate> pointList = new ArrayList<>();
		for (int i = 0; i < strPonts.length; i++) {
			String[] iStr = strPonts[i].split(",");
			if (iStr.length > 3) {
				pointList.add(new Coordinate(Double.parseDouble(iStr[1]), Double.parseDouble(iStr[2])));
			}
		}
		// 一个点以内，不处理
		if (pointList.size() <= 1) {
			return null;
		}
		// 检查最后一个点和第一个点是否一样
		Coordinate one = pointList.get(0);
		Coordinate last = pointList.get(pointList.size() - 1);
		if (one.getX() != last.getX() || one.getY() != last.getY()) {
			pointList.add(new Coordinate(one.getX(), one.getY()));
		}
		// 二个点以内，不处理
		if (pointList.size() <= 2) {
			return null;
		}

		Coordinate[] coords = new Coordinate[pointList.size()];
		coords = pointList.toArray(coords);
		GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
		LinearRing ring = geometryFactory.createLinearRing(coords);
		LinearRing holes[] = null; // use LinearRing[] to represent holes
		Polygon polygon = geometryFactory.createPolygon(ring, holes);

		SimpleFeatureType type = createFeatureType();
		// create the builder
		SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
		// add the values
		builder.add(polygon);
		// build the feature with provided ID
		SimpleFeature feature = builder.buildFeature("fid.1");

		List<SimpleFeature> rGraphic = new ArrayList<>();
		rGraphic.add(feature);
		return rGraphic;
	}

	private static SimpleFeatureType createFeatureType() throws NoSuchAuthorityCodeException, FactoryException {
		// 定义图形信息和属性信息
		SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
		// CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
		// tb.setCRS(crs);
		tb.setName("shapefile");
		tb.add("the_geom", Polygon.class);
		// build the type
		final SimpleFeatureType ftype = tb.buildFeatureType();
		return ftype;
	}

	/**
	 * 读取txt文件的内容
	 * 
	 * @param file
	 *            想要读取的文件对象
	 * @return 返回文件内容
	 */
	private static String txt2String(File file) {
		StringBuilder result = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				result.append(System.lineSeparator() + s);
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	/**
	 * 查询
	 * @return
	 */
	@Override
	public List<SimpleFeature> queryFeature(String source, String option, Geometry geometry) throws Exception {
		return null;
	}
	
	@Override
	public Boolean addFeatures(String source, List<SimpleFeature> datas, SimpleFeatureType metadata)
			throws IOException, NoSuchAuthorityCodeException, FactoryException {
		return false;
	}

	@Override
	public SimpleFeature updateFeature(String source, SimpleFeature row, SimpleFeatureType metadata) {
		return row;
	}

	@Override
	public Boolean deleteFeature(String source, String where) throws Exception {
		return false;
	}

	@Override
	public SimpleFeatureType getTableMetadata(String tableName) {
		return null;
	}
}